package com.gdd.videos.service.impl;

import com.gdd.videos.mapper.UserMapper;
import com.gdd.videos.pojo.User;
import com.gdd.videos.pojo.UserExample;
import com.gdd.videos.service.UserService;
import org.n3r.idworker.Sid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author zhangh     
 * @version V1.0.0
 * @projectName parent
 * @title     UserServiceImpl   
 * @package    com.gdd.videos.service.impl  
 * @date   2019/9/3 16:19  
 * @explain 用户服务层实现类
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    private Sid sid;


    /**
     * 根据用户名判断用户是否存在
     * @param username
     * @return true 存在   false   不存在
     */
    @Transactional(propagation = Propagation.SUPPORTS)
    public boolean queryUsernameIsExist(String username){
        UserExample userExample = new UserExample();
        userExample.createCriteria().andUsernameEqualTo(username);
        List<User> users = userMapper.selectByExample(userExample);
        // 判断用户是否存在,返回结果
        return 0 < users.size();
    }

    /**
     * 存储用户信息
     * @param user
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public void saveUser(User user){
        try {
            // 封装id
            user.setId(sid.nextShort());
            // 存储用户信息
            int i = userMapper.insertSelective(user);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据用户名查找用户信息
     * @param username
     * @return
     */
    @Transactional(propagation = Propagation.SUPPORTS)
    public User findByUserName(String username){
        // 封装查询条件
        UserExample userExample = new UserExample();
        userExample.createCriteria().andUsernameEqualTo(username);

        // 执行查询
        List<User> users = userMapper.selectByExample(userExample);

        // 返回结果
        if (users.size() > 0){
            return users.get(0);
        }else {
            return null;
        }
    }

    /**
     * 更新用户信息
     * @param user
     */
    public void updateUserInfo(User user){
        // 更新用户信息
        userMapper.updateByPrimaryKeySelective(user);
    }

    /**
     * 根据主键获取用户信息
     * @param userId
     * @return
     */
    public User findByUserId(String userId){
        User user = userMapper.selectByPrimaryKey(userId);
        return user;
    }

}
